package com.guigu.eduservice.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.guigu.eduservice.service.CaptchaService;
import com.guigu.eduservice.utils.RedisUtils;
import com.guigu.eduservice.vo.CaptchaVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * @Author: janecraft
 * @Date: 2025/6/28
 * @Description: com.guigu.aclservice.controller
 * @Version： 1.0
 */
@RestController
@RequestMapping("/advertisement/captcha")
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;
    @Autowired
    private DefaultKaptcha producer;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/get")
    public CaptchaVo getCaptcha() {
        // 生成验证码文本字符串
        String captcha = producer.createText();
        // 生成验证码对应的图片
        BufferedImage image = producer.createImage(captcha);

        // 将验证码图片转换成Base64编码的字符串
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        String str = "data:image/jpeg;base64,";
        String base64Img = str +
                Base64.getEncoder()
                        .encodeToString(outputStream.toByteArray())
                        .replace("\n","")
                        .replace("\r", "");

        // 缓存验证码
        CaptchaVo captchaVo = captchaService.cacheCaptcha(captcha);
        captchaVo.setBase64Img(base64Img);
        //通过key获取验证
        return captchaVo;
    }
    /**
     * 普通缓存获取
     *
     * @param captchavo 键
     * @return 值
     */
    @PostMapping("/get")
    public String getCaptcha(@RequestBody CaptchaVo captchavo) {
        // 直接获取值
        Object value = redisUtils.get(captchavo.getCaptchaKey());
        //将value全部设为大写
        value = value.toString().toUpperCase();
        //将value全部设为大写
        captchavo.setCaptcha(captchavo.getCaptcha().toUpperCase());
        //判断验证码是否正确
        if (value == null) {
            return "验证码已过期";
        }
        if (!value.equals(captchavo.getCaptcha())) {
            return "验证码错误";
        }
        return "ok";
    }
}
